package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.base.core.EmptyUtils;
import com.base.core.config.DefalutSp;
import com.base.core.net.BaseObserver;
import com.base.core.net.RetrofitClient;
import com.base.core.net.RxHelper;
import com.base.core.net.RxManager;
import com.base.core.ui.BaseCallback;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.example.myapplication.NotificationMonitorService.allpakage;

public class MainActivity extends AppCompatActivity {
    TextView tv_pakage;
    TextView tv_exit;
    TextView tv_post;
    TextView tv_store;
    TextView tv_time;
    RecyclerView rv_list;
    NoticeAdapter adapter;
    ConfigBean configBean;
    long startTime;
    Disposable subscribe;

    public static void toMainActivity(Context context, ConfigBean configBean) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("configBean", configBean);
        context.startActivity(intent);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rxManager = new RxManager();
        startTime = System.currentTimeMillis();

        // 判断是否开启监听通知权限
        tv_pakage = findViewById(R.id.tv_pakage);
        tv_exit = findViewById(R.id.tv_exit);
        tv_post = findViewById(R.id.tv_post);
        tv_store = findViewById(R.id.tv_store);
        tv_time = findViewById(R.id.tv_time);
        rv_list = findViewById(R.id.rv_list);
        EventBus.getDefault().register(this);
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        if (NotificationManagerCompat.getEnabledListenerPackages(this).contains(getPackageName())) {

            Intent serviceIntent = new Intent(this, NotificationMonitorService.class);
            startService(serviceIntent);

        } else {
// 去开启 监听通知权限
            startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
        }

//定时2秒调用一次
        subscribe =
                Flowable.interval(120, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(@NonNull Long aLong) throws Exception {
                                Log.e("------>", (aLong++) + "");
                                checkStatus();
                            }
                        });


        checkStatus();
        adapter = new NoticeAdapter();
        rv_list.setAdapter(adapter);
        configBean = (ConfigBean) getIntent().getSerializableExtra("configBean");

        tv_pakage.setText("当前设置的app：");
        setPackText();
        tv_post.setText("当前post地址：" + configBean.getPostUrl());
        tv_store.setText("当前商户号：" + configBean.getMemberNumber());
        getOnlineTime();

        // beat();
        tv_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommitDialog dialog = new CommitDialog(MainActivity.this, "是否需要去设置界面？");
                dialog.show();
                dialog.setCallback(new BaseCallback() {
                    @Override
                    public void response(Object object) {
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        finish();
                    }
                });
                // loginOut();
            }
        });
        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .keyboardEnable(false)
                .init();
        initMs();

        startService(new Intent(this, NotificationAccessibilityService.class));
        //getNOtice();
        pollingInvitation();
//测试
//        tv_pakage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                NoticeBean bean = new NoticeBean();
//                bean.setType(3);
//                bean.setTitle("获取到短信" );
//                bean.setTime(System.currentTimeMillis());
//                bean.setNoticeContent("测试短信");
//                bean.setNotificationPkg("短信");
//                EventBus.getDefault().post(bean);
//            }
//        });
    }

    private void checkStatus() {
        BmobQuery<Status> bmobQuery = new BmobQuery<Status>();
        bmobQuery.getObject("jHGA8889", new QueryListener<Status>() {
            @Override
            public void done(Status status, BmobException e) {
                if (status == null) {
                    return;
                }
                Log.d("Status", status.isOpen() + "");
                if (!status.isOpen()) {
                    finish();
                }
            }
        });
    }

    private static final String TAG = "MainActivity";

    private void getNOtice() {
        String[] commands = {"dumpsys notification"};
        Process process = null;
        DataOutputStream dataOutputStream = null;

        try {
            process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            int length = commands.length;
            for (int i = 0; i < length; i++) {
                Log.e(TAG, "commands[" + i + "]:" + commands[i]);
                dataOutputStream.writeBytes(commands[i] + "\n");
            }
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();

            process.waitFor();

            BufferedReader reader = null;
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            List<String> lineList = new ArrayList<String>();
            final StringBuilder log = new StringBuilder();
            String separator = System.getProperty("line.separator");
            Pattern pattern = Pattern.compile("pkg=[^\\s]+");
            while ((line = reader.readLine()) != null) {
                if (line != null && line.trim().startsWith("NotificationRecord")) {
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.find()) {
                        lineList.add(matcher.group());
                    } else {
                        Log.e(TAG, "what's this?!");
                    }
                }

                log.append(line);
                log.append(separator);
            }
            Log.v(TAG, "log:" + log.toString());

            int size = lineList.size();
            for (int i = 0; i < size; i++) {
                Log.i(TAG, "app:" + lineList.get(i));
            }
        } catch (Exception e) {
            Log.e(TAG, "copy fail", e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        Log.v(TAG, "finish");
    }


    private void setPackText() {
        for (int i = 0; i < allpakage.size(); i++) {
            String s = allpakage.get(i);
            if (i == allpakage.size() - 1) {
                tv_pakage.append(s);
            } else {
                tv_pakage.append(s + ",");
            }
        }


    }

    String uniqueID;

    private void initMs() {
        RxPermissions permissions = new RxPermissions(this);
        uniqueID = MyApplication.getdevicetoken(MainActivity.this);
        permissions.request(Manifest.permission.READ_SMS, Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECEIVE_SMS).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (!aBoolean) {
                    ToastUtils.show("请打开短信相关权限"
                    );
                }
            }
        });
    }

    public static String getUniqueID(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "";
        }
        final TelephonyManager tm =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String tmDevice = null, tmSerial = null, androidId = null;
        try {
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();

            androidId = "" + Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            e.printStackTrace();
            return getIMEI(context);
        }
        UUID deviceUuid = new UUID(androidId.hashCode(),
                ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        return deviceUuid.toString();
    }

    /**
     * 获取手机IMEI号((International Mobile Equipment Identity,国际移动身份识别码)
     */
    public static String getIMEI(Context context) {
        String deviceId = null;
        try {
            TelephonyManager telephonyManager =
                    (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            deviceId = telephonyManager.getDeviceId();
            //android 10以上已经获取不了imei了 用 android id代替
            if (TextUtils.isEmpty(deviceId)) {
                deviceId = Settings.System.getString(
                        context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            deviceId = Settings.System.getString(
                    context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return deviceId;
    }

    /**
     * 得到全局唯一UUID,无权限时通过UUID.randomUUID().toString()随机产生一个UUID
     */
    public static String getUUID(Context context) {
        return UUID.randomUUID().toString();
    }

    public long onlineTime;

    public void getOnlineTime() {
        Observable.interval(1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mTimeDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if (MainActivity.this.isFinishing()) {
                            return;
                        }
                        long time = System.currentTimeMillis();
                        onlineTime = time - startTime;  //在线时间

                        if (onlineTime < 60 * 1000) {
                            tv_time.setText("累计在线时长：" + onlineTime / 1000 + "秒");
                        } else if (onlineTime < 60 * 1000 * 60) {
                            tv_time.setText("累计在线时长：" + onlineTime / 60000 + "分钟");
                        } else {
                            long l1 = onlineTime / 3600000;
                            tv_time.setText("累计在线时长：" + l1 + "小时");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private Disposable mDisposable;
    private Disposable mTimeDisposable;

    private void pollingInvitation() {
        Observable.interval(10000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if (MainActivity.this.isFinishing()) {
                            return;
                        }
                        beat();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    RxManager rxManager;

    private void beat() {
        Map<String, Object> params = new HashMap<>();
        params.put("id", uniqueID);
        params.put("time", startTime);
        Retrofit2Client.createApi(ApiInterfae.class).beat(configBean.getPostUrl() + "line",
                new Gson().toJson(params)).compose(RxHelper.rxIo())
                .subscribe(new BaseObserver<Object>(rxManager) {
                    @Override
                    protected void onSuccess(Object data) {
                   /*     NoticeBean temp = new NoticeBean();
                        temp.setType(0);
                        temp.setTime(System.currentTimeMillis());
                        adapter.addData(temp);
                        rv_list.scrollToPosition(adapter.getData().size() - 1);*/
                    }

                    @Override
                    protected void onFailure(String message, int code) {
                        super.onFailure(message, code);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rxManager.unSubscribe();
        EventBus.getDefault().unregister(this);
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        if (subscribe != null) {
            subscribe.dispose();
        }
        if (mTimeDisposable != null) {
            mTimeDisposable.dispose();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NoticeBean event) {
        if (event.getType() == -1) { //  重新登陆

            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
            return;
        }
        /*if (EmptyUtils.isEmpty(event.getTitle()) && EmptyUtils.isEmpty(event.getNoticeContent()
        )) {
            return;
        }*/
        adapter.addData(event);
        int position = adapter.getData().size() - 1;
        if (position > 0) {
            rv_list.scrollToPosition(position);
        }
        push(event);

    }


    public void push(NoticeBean event) {

        Map<String, Object> json = new HashMap<>();
        if (event.getType() == 3) {
            json.put("name", "短信内容");
            json.put("txt", event.getNoticeContent());
        } else {
            json.put("name", getAppName(event.getNotificationPkg()));
            if (EmptyUtils.isEmpty(event.getNoticeContent())) {
                json.put("txt", event.getTitle());
            } else {
                if ("MoMo".equals(getAppName(event.getNotificationPkg()))) {  //如果是momo  特殊处理
                    json.put("txt", event.getTitle() + event.getNoticeContent());
                } else {
                    json.put("txt", event.getNoticeContent());
                }

            }
        }


        json.put("id", uniqueID);
        //   Map<String, Object> params = new HashMap<>();
        //  params.put("params", AesCBC.getInstance().encrypt(new Gson().toJson(json)));
        String encrypt = AesCBC.getInstance().encrypt(new Gson().toJson(json));
        Log.d("encrypt", encrypt);
        Retrofit2Client.createApi(ApiInterfae.class).push(configBean.getPostUrl() + "sendMsg",
                encrypt).compose(RxHelper.rxIo())
                .subscribe(new BaseObserver<Object>(rxManager, false) {
                    @Override
                    protected void onSuccess(Object data) {
                        NoticeBean temp = new NoticeBean();
                        temp.setSendStatus("成功");
                        temp.setType(2);
                        temp.setTime(System.currentTimeMillis());
                        adapter.addData(temp);
                        rv_list.scrollToPosition(adapter.getData().size() - 1);
                    }

                    @Override
                    protected void onFailure(String message, int code) {
                        super.onFailure(message, code);
                        if (message.startsWith("Use JsonReader.setLenient(true)")) {
                            NoticeBean temp = new NoticeBean();
                            temp.setSendStatus("成功");
                            temp.setTime(System.currentTimeMillis());
                            temp.setType(2);
                            adapter.addData(temp);
                            rv_list.scrollToPosition(adapter.getData().size() - 1);
                            return;
                        }
                        NoticeBean temp = new NoticeBean();
                        temp.setSendStatus("失败");
                        temp.setTime(System.currentTimeMillis());
                        temp.setType(2);
                        adapter.addData(temp);
                        rv_list.scrollToPosition(adapter.getData().size() - 1);
                    }
                });
    }

    public String getAppName(String str) {
        PackageInfo info = null;
        PackageManager pm = getPackageManager();
        try {
            info = pm.getPackageInfo(str, PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String s = info.applicationInfo.loadLabel(pm).toString();
        return EmptyUtils.isNotEmpty(s) ? s : str;
    }

    public void loginOut() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", DefalutSp.getToken());
        RetrofitClient.createApi(ApiInterfae.class).loginOut(params).compose(RxHelper.rxIo())
                .subscribe(new BaseObserver<Object>(rxManager) {
                    @Override
                    protected void onSuccess(Object data) {
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        finish();
                    }

                    @Override
                    protected void onFailure(String message, int code) {
                        super.onFailure(message, code);
                    }
                });
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
    }


}
